﻿console.log("Start Server Node JS");

var DistributionState = {
    TabUsers: new Array()
	, append: function (user, sock) {
	    var i;
	    for (i = 0; i < this.TabUsers.length; i++) {
	        if (this.TabUsers[i].login = user) { break; }
	    }
	    if (i == this.TabUsers.length) {
	        this.TabUsers.push({ login: user, platforms: new Array() });
	    }
	    this.TabUsers[i].platforms.push({ sock: sock });
	    this.send_update(i);
	}
	, remove: function (sock) {
	    for (index_user = 0; index_user < this.TabUsers.length; index_user++) {
	        for (i = 0; i < this.TabUsers[index_user].platforms.length; i++) {
	            if (this.TabUsers[index_user].platforms[i].sock == sock) {
	                this.TabUsers[index_user].platforms.splice(i, 1);
	                this.send_update(index_user);
	                return;
	            }
	        }
	    }
	}
	, send_update: function (index_user) {
	    var msg = "";
	    for (var i = 0; i < this.TabUsers[index_user].platforms.length; i++) {
	        msg = msg.concat(this.TabUsers[index_user].platforms[i].sock.id.toString() + "<br/>");
	    }
	    console.log(msg);

	    console.log("Emit for user indexed at " + index_user);
	    for (var i = 0; i < this.TabUsers[index_user].platforms.length; i++) {
	        console.log("\tplatform " + i);
	        this.TabUsers[index_user].platforms[i].sock.emit("update", { message: msg });
	        console.log("\tdone");
	    }
	}
}

var connect = require('connect')
  , fs = require("fs")
  , app = connect().use(connect.static('public'))
					.use(connect.bodyParser())
				    .use(function (req, res) {
				        if (req.method == "GET") {
				            res.writeHead(200, { 'Content-Type': 'application/xhtml+xml; charset=utf-8' });
				            fs.readFile(__dirname + '/login.xhtml',
                                 function (err, data) {
                                     if (err) {
                                         res.writeHead(500);
                                         return res.end('Error loading login.xhtml');
                                     }

                                     res.end(data);
                                 });
				        }
				        if (req.method == "POST") {
				            res.writeHead(200, { 'Content-Type': 'application/xhtml+xml; charset=utf-8' });
				            fs.readFile(__dirname + '/logged.xhtml',
                                 function (err, data) {
                                     if (err) {
                                         res.writeHead(500);
                                         return res.end('Error loading logged.xhtml');
                                     }

                                     res.write(data.toString().replace(/__LOGIN__/g, req.body.login));
                                     res.end();
                                 });

				        }
				    })
					.listen(8080)
  , io = require('socket.io').listen(app);


io.sockets.on('connection', function (socket) {
    console.log("coucou un nouveau client : " + socket.id);
    socket.on('identification', function (data) {
        console.log("Received identification from " + socket.id + " :");
        console.log(data);
        DistributionState.append(data.login, socket);
    });
    socket.on('disconnect', function (data) {
        DistributionState.remove(socket);
    }
      );
});


console.log("End init server");